<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useHttp } from "@/hooks/useHttp";
import {
  type SendGoodLogDto,
  getDonateGoodPageApi,
  type DonateGoodReq,
  donateGoodApi,
} from "@/api/donate";
import {
  getGoodCategoriesApi,
  type GoodsCategoryRecord,
  checkGoodIdApi,
  type GoodInfo,
  getGoodPageApi,
} from "@/api/good";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { Loading, CircleCheck } from "@element-plus/icons-vue";
import { checkUserNoApi } from "@/api/user";

// 查询参数
interface SearchType {
  userNo: string;
  category: string;
  operator: string;
  day: number | null;
}

const searchParams = ref<SearchType>({
  userNo: "",
  category: "",
  operator: "",
  day: null,
});

// 赠送物品相关
const addGoodDialogVisible = ref(false);
const addGoodLoading = ref(false);
const addGoodFormRef = ref<FormInstance>();
const goodList = ref<GoodInfo[]>([]);

const addGoodForm = reactive({
  userNo: "",
  goodId: "",
  day: undefined as number | undefined,
  reason: "",
  category: "",
});

// 用户编号校验相关
const userNoValidating = ref(false);
const userNoValid = ref(false);
const currentUserInfo = ref<{
  avatar?: string;
  nickname?: string;
}>({});

// 物品ID校验相关
const goodIdValidating = ref(false);
const goodIdValid = ref(false);
const currentGoodInfo = ref<GoodInfo | null>(null);

// 物品类型选项
const categoryOptions = ref<GoodsCategoryRecord[]>([]);

// 用户编号校验函数
const validateUserNo = async (userNo: string) => {
  if (!userNo) {
    userNoValid.value = false;
    currentUserInfo.value = {};
    return;
  }

  try {
    userNoValidating.value = true;
    const response = await checkUserNoApi(userNo);
    if (response.code === 200 && response.data) {
      userNoValid.value = true;
      // 保存用户信息
      currentUserInfo.value = {
        avatar: response.data.avatar,
        nickname: response.data.nickname,
      };
    } else {
      userNoValid.value = false;
      currentUserInfo.value = {};
    }
  } catch (error) {
    userNoValid.value = false;
    currentUserInfo.value = {};
    console.error("用户编号验证失败:", error);
  } finally {
    userNoValidating.value = false;
  }
};

// 物品ID校验函数
const validateGoodId = async (goodId: string) => {
  if (!goodId) {
    goodIdValid.value = false;
    currentGoodInfo.value = null;
    return;
  }

  try {
    goodIdValidating.value = true;
    const response = await checkGoodIdApi(goodId);
    if (response.code === 200 && response.data) {
      goodIdValid.value = true;
      // 保存物品信息
      currentGoodInfo.value = response.data;
    } else {
      goodIdValid.value = false;
      currentGoodInfo.value = null;
    }
  } catch (error) {
    goodIdValid.value = false;
    currentGoodInfo.value = null;
    console.error("物品ID验证失败:", error);
  } finally {
    goodIdValidating.value = false;
  }
};

// 赠送物品表单验证规则
const addGoodRules: FormRules = {
  userNo: [
    { required: true, message: "请输入用户编号", trigger: "blur" },
    {
      validator: async (rule: any, value: string, callback: any) => {
        if (!value) {
          callback();
          return;
        }

        await validateUserNo(value);

        if (userNoValid.value) {
          callback();
        } else {
          callback(new Error("用户编号不存在"));
        }
      },
      trigger: "blur",
    },
  ],
  goodId: [
    { required: true, message: "请输入物品名称", trigger: "blur" },
    // {
    //   validator: async (rule: any, value: string, callback: any) => {
    //     if (!value) {
    //       callback();
    //       return;
    //     }

    //     await validateGoodId(value);

    //     if (goodIdValid.value) {
    //       callback();
    //     } else {
    //       callback(new Error("物品ID不存在"));
    //     }
    //   },
    //   trigger: "blur",
    // },
  ],
  day: [{ required: true, message: "请选择天数", trigger: "change" }],
  reason: [{ required: true, message: "请输入赠送原因", trigger: "blur" }],
};

// 使用封装的 useHttp hook，配置自定义参数名
const {
  dataList,
  loading,
  totals,
  pageInfo,
  loadData,
  handleSizeChange,
  handleCurrentChange,
  resetPagination,
} = useHttp<SendGoodLogDto>("/donate/goodPage", searchParams, {
  pageKey: "pageIndex", // 使用 pageIndex 而不是 page
  pageSizeKey: "pageSize", // 使用 pageSize
  totalKey: "total", // 使用 total
  listKey: "list", // 使用 list
});

// 查询方法
const handleSearch = () => {
  resetPagination();
  // resetPagination() 内部已经调用了 loadData()，不需要重复调用
};

// 重置方法
const handleReset = () => {
  searchParams.value = {
    userNo: "",
    category: "",
    operator: "",
    day: null,
  };
  resetPagination();
  // resetPagination() 内部已经调用了 loadData()，不需要重复调用
};

// 获取物品类型标签颜色
const getCategoryTagType = (category: string) => {
  switch (category) {
    case "badge":
      return "success"; // 绿色
    case "head_portrait_box":
      return "warning"; // 橙色
    case "bubble_box":
      return "info"; // 蓝色
    case "vehicle":
      return "danger"; // 红色
    case "wave":
      return "success"; // 绿色
    case "bubble":
      return "warning"; // 橙色
    case "user_card":
      return "info"; // 蓝色
    case "entry_float":
      return "danger"; // 红色
    default:
      return "info"; // 蓝色
  }
};

// 加载物品分类数据
const loadCategories = async () => {
  try {
    const response = await getGoodCategoriesApi();
    if (response.code === 200) {
      categoryOptions.value = response.data;
    }
  } catch (error) {
    console.error("加载物品分类失败:", error);
    ElMessage.error("加载物品分类失败");
  }
};

const getGoodList = async () => {
  const params = {
    category: addGoodForm.category,
    pageNum: 1,
    pageSize: 1000,
  };

  // 过滤空值参数
  const requestParams = Object.fromEntries(
    Object.entries(params).filter(([_, value]) => {
      return value !== "" && value !== null && value !== undefined;
    })
  );

  const response = await getGoodPageApi(requestParams);
  const { data } = response;
  goodList.value = data.list;
};

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 打开赠送物品弹窗
const handleAddGood = () => {
  addGoodDialogVisible.value = true;
};

// 用户编号输入变化处理
const handleUserNoChange = async (value: string) => {
  // 清空之前的用户信息
  currentUserInfo.value = {};
  userNoValid.value = false;

  if (value) {
    // 添加防抖，避免频繁请求
    setTimeout(() => {
      if (addGoodForm.userNo === value) {
        validateUserNo(value);
      }
    }, 500);
  }
};

const handleCategoryChange = () => {
  addGoodForm.goodId = "";
  getGoodList();
}

// 物品ID输入变化处理
const handleGoodIdChange = async (value: string) => {
  // 清空之前的物品信息
  currentGoodInfo.value = null;
  goodIdValid.value = false;

  if (value) {
    // 添加防抖，避免频繁请求
    setTimeout(() => {
      if (addGoodForm.goodId === value) {
        validateGoodId(value);
      }
    }, 500);
  }
};

// 取消赠送物品
const handleCancelAddGood = () => {
  addGoodDialogVisible.value = false;
  // 重置表单
  Object.assign(addGoodForm, {
    userNo: "",
    goodId: "",
    day: undefined,
    reason: "",
    category: ""
  });
  // 重置用户编号校验状态
  userNoValid.value = false;
  userNoValidating.value = false;
  currentUserInfo.value = {};
  // 重置物品ID校验状态
  goodIdValid.value = false;
  goodIdValidating.value = false;
  currentGoodInfo.value = null;
  addGoodFormRef.value?.clearValidate();
};

// 确认赠送物品
const handleConfirmAddGood = async () => {
  if (!addGoodFormRef.value) return;

  try {
    await addGoodFormRef.value.validate();
    addGoodLoading.value = true;

    const requestData: DonateGoodReq = {
      userNo: addGoodForm.userNo,
      goodId: addGoodForm.goodId,
      day: addGoodForm.day!,
      reason: addGoodForm.reason,
    };

    await donateGoodApi(requestData);
    ElMessage.success("物品赠送成功");
    addGoodDialogVisible.value = false;

    // 刷新列表
    loadData();
  } catch (error) {
    console.error("赠送物品失败:", error);
    ElMessage.error("赠送物品失败");
  } finally {
    addGoodLoading.value = false;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadCategories();
  loadData(); // 手动调用加载数据
  getGoodList();
});
</script>

<template>
  <div class="send-good">
    <!-- 查询区域 -->
    <el-card class="mb">
      <el-form :model="searchParams" inline>
        <el-form-item label="用户编号">
          <el-input
            v-model="searchParams.userNo"
            placeholder="请输入用户编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="物品类型">
          <el-select
            v-model="searchParams.category"
            placeholder="请选择物品类型"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.key"
              :label="item.desc"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="操作者">
          <el-input
            v-model="searchParams.operator"
            placeholder="请输入操作者"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="天数">
          <el-select
            v-model="searchParams.day"
            placeholder="请选择天数"
            clearable
            style="width: 200px"
          >
            <el-option label="1天" :value="1" />
            <el-option label="3天" :value="3" />
            <el-option label="5天" :value="5" />
            <el-option label="7天" :value="7" />
            <el-option label="10天" :value="10" />
            <el-option label="15天" :value="15" />
            <el-option label="30天" :value="30" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAddGood">赠送物品</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <el-table
        :data="dataList"
        v-loading="loading"
        style="width: 100%"
        :fit="true"
      >
        <el-table-column
          prop="id"
          label="记录ID"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="userNo" label="用户编号" min-width="120" />
        <el-table-column prop="goodName" label="物品名称" min-width="120" />
        <el-table-column
          prop="category"
          label="物品类型"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getCategoryTagType(row.category)">
              {{
                categoryOptions.find((item) => item.key === row.category)
                  ?.desc || row.category
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="subCategory"
          label="子类型"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span>{{ row.subCategory || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="day" label="天数" width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.day }}天</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="reason"
          label="原因"
          min-width="150"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span>{{ row.reason || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作者" min-width="120" />
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="200"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="modifyTime"
          label="修改时间"
          min-width="200"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ formatDateTime(row.modifyTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        class="pagination-center mt mb"
        v-model:current-page="pageInfo.page"
        v-model:page-size="pageInfo.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="sizes, prev, pager, next, jumper, total"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </el-card>

    <!-- 赠送物品弹窗 -->
    <el-dialog
      v-if="addGoodDialogVisible"
      v-model="addGoodDialogVisible"
      title="赠送物品"
      width="500px"
      :close-on-click-modal="false"
      @close="handleCancelAddGood"
    >
      <el-form
        ref="addGoodFormRef"
        :model="addGoodForm"
        :rules="addGoodRules"
        label-width="100px"
      >
        <el-form-item label="用户编号" prop="userNo">
          <el-input
            v-model="addGoodForm.userNo"
            placeholder="请输入用户编号"
            clearable
            :loading="userNoValidating"
            @blur="handleUserNoChange"
          >
            <template #suffix>
              <el-icon v-if="userNoValidating" class="is-loading">
                <Loading />
              </el-icon>
              <el-icon v-else-if="userNoValid" style="color: #67c23a">
                <CircleCheck />
              </el-icon>
            </template>
          </el-input>
          <!-- 用户信息显示 -->
          <div
            v-if="userNoValid && currentUserInfo.nickname"
            class="user-info-display"
          >
            <el-avatar
              :size="32"
              :src="currentUserInfo.avatar"
              class="user-avatar"
            />
            <span class="user-nickname">{{ currentUserInfo.nickname }}</span>
          </div>
        </el-form-item>

        <!-- 物品信息显示 -->
        <!-- <el-form-item label="物品" prop="goodId">
          <el-input
            v-model="addGoodForm.goodId"
            placeholder="请输入物品ID"
            clearable
            :loading="goodIdValidating"
            @input="handleGoodIdChange"
          >
            <template #suffix>
              <el-icon v-if="goodIdValidating" class="is-loading">
                <Loading />
              </el-icon>
              <el-icon v-else-if="goodIdValid" style="color: #67c23a">
                <CircleCheck />
              </el-icon>
            </template>
          </el-input>

          <div v-if="goodIdValid && currentGoodInfo" class="good-info-display">
            <el-image
              :src="currentGoodInfo.previewImageUrl"
              :preview-src-list="[currentGoodInfo.previewImageUrl]"
              fit="cover"
              class="good-image"
              style="width: 40px; height: 40px; border-radius: 4px"
            />
            <div class="good-details">
              <div class="good-name">{{ currentGoodInfo.name.en }}</div>
              <div class="good-id">ID: {{ addGoodForm.goodId }}</div>
              <div class="good-category">
                分类:
                {{
                  categoryOptions.find(
                    (item) => item.key === currentGoodInfo.category
                  )?.desc || currentGoodInfo.category
                }}
              </div>
            </div>
          </div>
        </el-form-item> -->

        <el-form-item label="物品类型" prop="category">
          <el-select
            v-model="addGoodForm.category"
            placeholder="请选择物品类型"
            @change="handleCategoryChange"
            clearable
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.key"
              :label="item.desc"
              :value="item.key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="物品名称" prop="goodId">
          <el-select
            v-model="addGoodForm.goodId"
            placeholder="请选择物品名称"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in goodList"
              :key="item.id"
              :label="item.name.zh"
              :value="item.id"
              style="height: auto; padding: 10px 16px;"
            >
              <div class="option-content" style="display: flex; align-items: center;">
                <el-image
                  :src="item.previewImageUrl"
                  :preview-src-list="[item.previewImageUrl]"
                  fit="cover"
                  class="option-image"
                  style="
                    width: 24px;
                    height: 24px;
                    margin-right: 8px;
                    border-radius: 4px;
                    object-fit: cover;
                  "
                />
                <span style="line-height: 24px;">{{ item.name.zh }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="天数" prop="day">
          <el-select
            v-model="addGoodForm.day"
            placeholder="请选择天数"
            clearable
            style="width: 100%"
          >
            <el-option label="1天" :value="1" />
            <el-option label="3天" :value="3" />
            <el-option label="5天" :value="5" />
            <el-option label="7天" :value="7" />
            <el-option label="10天" :value="10" />
            <el-option label="15天" :value="15" />
            <el-option label="30天" :value="30" />
          </el-select>
        </el-form-item>

        <el-form-item label="原因" prop="reason">
          <el-input
            v-model="addGoodForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入赠送原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelAddGood">取消</el-button>
          <el-button
            type="primary"
            :loading="addGoodLoading"
            @click="handleConfirmAddGood"
          >
            确定赠送
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
.send-good {
  font-size: 16px;

  .mb {
    margin-bottom: 20px;
  }

  .mt {
    margin-top: 20px;
  }

  .pagination-center {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  // 表格字体大小和行间距
  :deep(.el-table) {
    font-size: 16px;

    .el-table__header {
      th {
        font-size: 16px;
        font-weight: 600;
        padding: 16px 0; // 增加表头行高
      }
    }

    .el-table__body {
      td {
        font-size: 16px;
        padding: 16px 0; // 增加表格行高
      }

      tr {
        height: auto; // 让行高自适应内容
      }
    }

    // 增加行间距
    .el-table__row {
      height: 60px; // 设置固定的行高
    }
  }

  // 表单字体大小
  :deep(.el-form) {
    .el-form-item__label {
      font-size: 16px;
    }

    .el-input__inner {
      font-size: 16px;
    }

    .el-select .el-input__inner {
      font-size: 16px;
    }
  }

  // 按钮字体大小
  :deep(.el-button) {
    font-size: 16px;
  }

  // 分页字体大小
  :deep(.el-pagination) {
    font-size: 16px;
  }

  // 弹窗样式
  .dialog-footer {
    text-align: right;
  }

  // 用户信息显示样式
  .user-info-display {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 8px;
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    border: 1px solid #e4e7ed;

    .user-avatar {
      flex-shrink: 0;
    }

    .user-nickname {
      font-size: 14px;
      color: #606266;
      font-weight: 500;
    }
  }

  // 物品信息显示样式
  .good-info-display {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-top: 8px;
    padding: 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    border: 1px solid #e4e7ed;

    .good-image {
      flex-shrink: 0;
      border: 1px solid #e4e7ed;
    }

    .good-details {
      flex: 1;

      .good-name {
        font-size: 14px;
        color: #303133;
        font-weight: 500;
        margin-bottom: 4px;
      }

      .good-id {
        font-size: 12px;
        color: #909399;
        margin-bottom: 2px;
      }

      .good-category {
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .option-content {
    display: flex;
    align-items: center;
  }

  // 图片样式
  .option-image {
    // width: 24px;
    // height: 24px;
    // margin-right: 8px;
    // border-radius: 4px;
    // object-fit: cover;
  }
}
</style>
